package cn.jjzd.user.service;

import cn.jjzd.common.utils.NumberUtils;
import cn.jjzd.user.pojo.User;
import cn.jjzd.user.mapper.UserMapper;
import cn.jjzd.user.utils.CodecUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String KEY_PREFIX = "user:verfiy:";

    /**
     * 校验数据是否可用
     * @param data
     * @param type 1用户名 2手机
     * @return
     */
    public Boolean checkData(String data, Integer type) {
        User user = new User();
        if(type == 1){
            //user.setUsername(data);
        }else if(type == 2){
            //user.setPhone(data);
        }else{
            return null;
        }
        return this.userMapper.selectCount(user) == 0;
    }

    public void sendVerifyCode(String phone) {
        if(StringUtils.isBlank(phone)){
            return;
        }
        //生产验证码
        String code = NumberUtils.generateCode(6);

        //发送消息到rabbitMQ
        Map<String,String> map = new HashMap<>();
        map.put("phone",phone);
        map.put("code",code);
        this.amqpTemplate.convertAndSend("JJZD.SMS.EXCHANGE","SMS.VERIFY.CODE",map);

        //把验证码保存到redis中
        this.redisTemplate.opsForValue().set(KEY_PREFIX+phone,code,5, TimeUnit.MINUTES);
    }

    public void register(User user, String code) {
        //查询redis中的验证码
        String redisCode = this.redisTemplate.opsForValue().get(KEY_PREFIX+user.getPhone());
        //校验验证码
        if(!StringUtils.equals(code,redisCode)){
            return;
        }
        //生产盐 salt
        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);
        //加盐加密
        user.setPassword(CodecUtils.md5Hex(user.getPassword(),salt));
        //新增用户
        user.setId(null);
        user.setCreated(new Date());
        this.userMapper.insertSelective(user);
    }

    public User queryUser(String username, String password) {
        User user = new User();
        user.setUsername(username);
        User orginUser = this.userMapper.selectOne(user);

        //判断是否为空
        if(orginUser != null){
            return null;
        }

        //获取盐，对用户输入的密码加盐加密
        password = CodecUtils.md5Hex(password,user.getSalt());

        //和数据库中的密码比较
        if(StringUtils.equals(password,user.getPassword())){
            return user;
        }
        return null;
    }
}
